package edu.sias.hyznxfapi.controller;

import com.google.gson.Gson;
import edu.sias.hyznxfapi.face.detect.iflytek.WebFaceDetect;
import edu.sias.hyznxfapi.face.login.iflytek.WebFaceCompare;
import edu.sias.hyznxfapi.vo.ImageVo;
import edu.sias.common.core.domain.AjaxResult;
import edu.sias.common.core.domain.entity.SysUser;
import edu.sias.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;

import static edu.sias.common.core.domain.AjaxResult.error;
import static edu.sias.common.core.domain.AjaxResult.success;


@RestController
@RequestMapping("/xfapi/face")
public class XfApiFaceController {
    @Autowired
    private ISysUserService userService;

    //内部类用来获取人脸比对结果
    class FaceCompareResult {
        int ret;
        double score;
    }

    /**
     * 查询人脸库信息
     * @param imageVo
     * @return
     */
    @PostMapping("/find")
    public AjaxResult find(@RequestBody ImageVo imageVo) throws Exception {
        double score1 = 0;
        //获取到前端传过来的要验证的图片编码
        String imageUrl = imageVo.getImageUrl();
        System.out.println("imageUrl = " + imageUrl);
        //获取后端数据库中本人存的图片编码
        //先获取到是哪个人
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        //获取是否导入了人脸信息
        SysUser sysUser = userService.selectUserByUserName(name);
        int faceCode = sysUser.getFaceCode();
        if (faceCode == 0) {
            return error("尚未录入人脸信息");
        }
        //获取后端数据库中本人存的图片编码
        String faceUrl = sysUser.getFaceUrl();
        WebFaceCompare demo = new WebFaceCompare();
        WebFaceCompare.ResponseData respData = demo.faceContrast(imageUrl, faceUrl);
        if (respData != null && respData.getPayLoad().getFaceCompareResult() != null) {
            String textBase64 = respData.getPayLoad().getFaceCompareResult().getText();
            String text = new String(Base64.getDecoder().decode(textBase64));
            System.out.println("人脸比对结果(text)base64解码后：");
            System.out.println(text);
            // 使用Gson将JSON字符串转换为Java对象
            Gson gson = new Gson();
            FaceCompareResult result = gson.fromJson(text, FaceCompareResult.class);
            // 提取并打印score值
            double score = result.score;
            System.out.println("人脸比对结果(score)：");
            System.out.println(score);
            score1 = score;
        }
        if (score1 >= 0.67){
            //先获取到是哪个人
            String name1 = SecurityContextHolder.getContext().getAuthentication().getName();
            System.out.println("name = " + name1); //user_name
            SysUser sysUser1 = userService.selectUser(name);
            return success(sysUser1);
        }else {
            return error("人脸比对失败");
        }
    }
    /**
     * 注册/更新人脸信息
     * @param imageVo
     * @return
     */
    @PostMapping("/registration")
    public String upload(@RequestBody ImageVo imageVo) throws Exception {
        //获取到前端传过来的要验证的图片编码
        String imageUrl = imageVo.getImageUrl();
        System.out.println("imageUrl = " + imageUrl);
        //获取后端数据库中本人存的图片编码
        //先获取到是哪个人
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("name = " + name); //user_name
        //添加
        String s = new WebFaceDetect().detectFace(imageUrl);
        // 按照"+"进行拆分
        String[] parts = s.split("\\+");
        // 现在parts数组将包含两个元素：第一个元素是faceNum1，第二个元素是score1
        String faceNumStr = parts[0];
        double score = Double.parseDouble(parts[1]);
        // 输出结果
        System.out.println("人脸数量(faceNum): " + faceNumStr);
        System.out.println("得分(score): " + score);
        if (faceNumStr == "0"){
            //没有监测到人脸
            return "3";
        }
        if (score < 0.67){
            //人脸质量太差，重新输入
            return "2";
        }
        Boolean or = userService.add(name,imageUrl);
        if (or){
            //成功
            return "1";
        }else {
            //失败
            return "0";
        }
    }

    /**
     * 删除人脸信息
     * @return
     */
    @DeleteMapping("/delete")
    public String delete() {
        //先获取到是哪个人
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("name = " + name); //user_name
        //添加
        SysUser sysUser = userService.selectUser(name);
        int faceCode = sysUser.getFaceCode();
        if (faceCode == 0){
            //尚未录入，请先录入
            return "2";
        }
        Boolean or = userService.delete(name);
        if (or){
            return "1";
        }else {
            return "0";
        }
    }

    /**
     * 获取所有的登陆人的用户信息（附带人脸）
     * @return
     */
    @GetMapping("/getFaceUser")
    public AjaxResult getFaceUser() {
        //先获取到是哪个人
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("name = " + name); //user_name
        SysUser sysUser = userService.selectUser(name);
        System.out.println("sysUser = " + sysUser);
        return success(sysUser);
    }
    }
